package com.jservice.web.sysRole;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Record;
import com.jservice.framework.annotation.RouteBind;
import com.jservice.framework.authc.AuthcUtil;
import com.jservice.framework.dto.Message;
import com.jservice.framework.dto.Pager;
import com.jservice.model.SysRole;
import com.jservice.web.base.JBaseController;

/**
 * RoleController
 *
 * @author cwvian
 * @version 1.0
 * @date 2017/5/4
 */
@RouteBind(path = "/admin/role")
public class RoleController extends JBaseController {


	public void list(){
		Pager pager = SysRoleService.me().findPage(getPageable());

		setAttr("pager",pager);
		render("list");
	}

	public void add(){
		setAttr("permissions",AuthcUtil.getAllAuthcConfigs());
		render("add");
	}

	@Before(RoleValidator.class)
	public void save(){

		String[] permissions = getParaValues("permissions");
		SysRole role = getModel(SysRole.class);

		if(SysRoleService.me().savePermission(role,permissions)){
			setFlashMessage(Message.success("角色添加成功"));
		}else{
			setFlashMessage(Message.error("角色添加失败"));
		}
		redirect("/admin/role/list");
	}

	public void edit(){
		String roldId = getPara("id");
		Record role = SysRoleService.me().findById(roldId);
		setAttr("role",role);
		render("edit");
	}

	@Before(RoleValidator.class)
	public void update(){
		String[] permissions =getParaValues("permissions");
		SysRole role = getModel(SysRole.class,"sysRole");
		if(SysRoleService.me().updatePermission(role,permissions)){
			setFlashMessage(Message.success("角色修改成功"));
		}else{
			setFlashMessage(Message.error("角色修改失败"));
		}
		redirect("/admin/role/list");
	}

	public void delete(){
		String[] ids = getParaValues("ids");

		if (ids != null) {
			for (String id : ids) {
				Record role = SysRoleService.me().findById(id);
				if (role != null && (role.getBoolean("is_system") || !role.getBoolean("is_delete") )) {
					renderJson(Message.error("不允许删除"));
					return;
				}
			}
			for(String id : ids){
				SysRoleService.DAO.deleteById(id);
			}
		}
		renderJson(Message.success("删除成功"));
	}


}
